<template>
  <div class="navicate-content">
    <el-menu :default-active="defaultActive" router>
      <div v-for="father in tableData">
        <el-sub-menu v-if="father.children.length > 0" :index="father.path">
          <template #title>
            <el-icon><component :is="father.icon" /></el-icon>
            <span>{{ father.name }}</span>
          </template>
          <el-menu-item v-for="child in father.children" :index="child.path">
            <template #title>
              <el-icon><component :is="child.icon" /></el-icon>
              <span>{{ child.name }}</span>
            </template>
          </el-menu-item>
        </el-sub-menu>
        <el-menu-item v-else :index="father.path">
          <template #title>
            <el-icon><component :is="father.icon" /></el-icon>
            <span>{{ father.name }}</span>
          </template>
        </el-menu-item>
      </div>
    </el-menu>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRoute } from "vue-router";
import api from "@/api";
const route = useRoute();

const menus = ref([]);
const tableData = ref([]);
const defaultActive = ref(null);

const initMenus = async () => {
  if (menus.value.length == 0) {
    const res = await api.menus.getMenus();
    menus.value = res.menus.sort((a, b) => {
      return a.sort - b.sort;
    });
  }
};

const initTableData = () => {
  let fathers = menus.value.filter((f) => f.father == 0);
  const childrens = menus.value.filter((f) => f.father != 0);
  for (let index = 0; index < fathers.length; index++) {
    fathers[index].children = [];
    fathers[index].children = childrens.filter(
      (c) => c.father == fathers[index].id
    );
  }
  tableData.value = fathers;
};

const initDefaultActive = ()=> {
    defaultActive.value = route.path;
}

onMounted(async () => {
  await initMenus();
  initTableData();
  initDefaultActive()
});
</script>

<style scoped>
.navicate-content {
  width: 100%;
  height: 100%;
  user-select: none;
}
</style>
